package com.ruoyi.common.utils.ps2;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ImageAndExcelRenamer {

    // 配置参数
    private static final String EXCEL_PATH = "D:\\BaiduNetdiskDownload\\0806-226\\metadata.xlsx";
    private static final String IMAGE_FOLDER = "D:\\BaiduNetdiskDownload\\0806-226\\处理图";
    private static final String SUFFIX = "-1"; // 要添加的后缀

    public static void main(String[] args) {
        try {
            System.out.println("开始处理图片和Excel重命名...");

            // 1. 读取Excel数据并获取A列到B列的映射
            Map<String, String> nameMap = readExcelData(EXCEL_PATH);
            System.out.println("成功读取Excel数据，共 " + nameMap.size() + " 条记录");

            // 2. 重命名图片
            Map<String, String> renameMap = renameImages(nameMap);
            System.out.println("成功重命名 " + renameMap.size() + " 张图片");

            // 3. 更新Excel文件中的B列
            updateExcelFile(EXCEL_PATH, renameMap);
            System.out.println("成功更新Excel文件");

            System.out.println("处理完成！");
        } catch (Exception e) {
            System.err.println("处理过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 读取Excel文件并构建名称映射关系
     * A列 -> B列
     */
    private static Map<String, String> readExcelData(String excelPath) throws IOException {
        Map<String, String> nameMap = new HashMap<>();
        FileInputStream inputStream = new FileInputStream(excelPath);

        try (Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                // 跳过标题行
                if (row.getRowNum() == 0) continue;

                Cell originalCell = row.getCell(0); // A列
                Cell editedCell = row.getCell(1);   // B列

                if (originalCell != null && editedCell != null) {
                    String originalName = getCellValueAsString(originalCell).trim();
                    String editedName = getCellValueAsString(editedCell).trim();

                    if (!originalName.isEmpty() && !editedName.isEmpty()) {
                        nameMap.put(originalName, editedName);
                    }
                }
            }
        } finally {
            inputStream.close();
        }

        return nameMap;
    }

    /**
     * 重命名图片并返回重命名映射关系
     */
    private static Map<String, String> renameImages(Map<String, String> nameMap) {
        File imageDir = new File(IMAGE_FOLDER);
        File[] files = imageDir.listFiles();
        Map<String, String> renameMap = new HashMap<>(); // 存储原文件名到新文件名的映射

        if (files == null) {
            System.err.println("图片文件夹中没有文件或路径错误: " + IMAGE_FOLDER);
            return renameMap;
        }

        for (File imageFile : files) {
            if (isImageFile(imageFile)) {
                String fileName = getFileNameWithoutExtension(imageFile.getName());

                // 找到对应的A列值
                String originalName = findOriginalName(fileName, nameMap);

                if (originalName != null) {
                    try {
                        // 构建新文件名
                        String newBaseName = originalName + SUFFIX;
                        String newName = newBaseName + getFileExtension(imageFile.getName());
                        File newFile = new File(imageDir, newName);

                        // 处理文件名冲突
                        int counter = 1;
                        while (newFile.exists()) {
                            newName = newBaseName + "_" + counter + getFileExtension(imageFile.getName());
                            newFile = new File(imageDir, newName);
                            counter++;
                        }

                        // 重命名文件
                        if (imageFile.renameTo(newFile)) {
                            System.out.println("重命名图片: " + imageFile.getName() + " → " + newName);
                            // 存储映射关系: 原文件名 -> 新文件名(不带扩展名)
                            renameMap.put(fileName, getFileNameWithoutExtension(newName));
                        } else {
                            System.err.println("重命名失败: " + imageFile.getName());
                        }
                    } catch (Exception e) {
                        System.err.println("处理图片 '" + imageFile.getName() + "' 时出错: " + e.getMessage());
                    }
                } else {
                    System.out.println("图片 '" + imageFile.getName() + "' 不在Excel记录中，跳过处理");
                }
            }
        }

        return renameMap;
    }

    /**
     * 根据B列的值找到对应的A列值
     */
    private static String findOriginalName(String fileName, Map<String, String> nameMap) {
        for (Map.Entry<String, String> entry : nameMap.entrySet()) {
            if (entry.getValue().equals(fileName)) {
                return entry.getKey();
            }
        }
        return null;
    }

    /**
     * 更新Excel文件中的B列
     */
    private static void updateExcelFile(String excelPath, Map<String, String> renameMap) throws IOException {
        FileInputStream inputStream = new FileInputStream(excelPath);
        Workbook workbook = null;

        try {
            workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                // 跳过标题行
                if (row.getRowNum() == 0) continue;

                Cell editedCell = row.getCell(1); // B列
                if (editedCell == null) continue;

                String editedName = getCellValueAsString(editedCell).trim();
                if (editedName.isEmpty()) continue;

                // 检查是否有重命名记录
                if (renameMap.containsKey(editedName)) {
                    String newName = renameMap.get(editedName);
                    editedCell.setCellValue(newName);
                    System.out.println("更新Excel: (" + editedName + ") → (" + newName + ")");
                }
            }

            // 保存修改
            FileOutputStream out = new FileOutputStream(excelPath);
            workbook.write(out);
            out.close();
        } finally {
            if (workbook != null) {
                workbook.close();
            }
            inputStream.close();
        }
    }

    // ===== 工具方法 =====
    private static String getCellValueAsString(Cell cell) {
        if (cell == null) return "";

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 检查是否为整数
                    double numValue = cell.getNumericCellValue();
                    if (Math.floor(numValue) == numValue) {
                        return String.valueOf((int) numValue);
                    } else {
                        return String.valueOf(numValue);
                    }
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    private static boolean isImageFile(File file) {
        String name = file.getName().toLowerCase();
        return name.endsWith(".jpg") || name.endsWith(".jpeg") ||
                name.endsWith(".png") || name.endsWith(".gif") ||
                name.endsWith(".bmp") || name.endsWith(".webp");
    }

    private static String getFileNameWithoutExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
    }

    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "" : fileName.substring(dotIndex);
    }
}